package com.tempjob.common.utils;

import com.tempjob.common.exception.BusinessException;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class AES {

    private static final Logger LOGGER = LoggerFactory.getLogger(AES.class);

    private static boolean initialized = false;

    /**
     * AES解密
     *
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("AES decrypt error:",e);
//            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            LOGGER.error("AES decrypt error:",e);
        } catch (InvalidKeyException e) {
            LOGGER.error("AES decrypt error:",e);
        } catch (IllegalBlockSizeException e) {
            LOGGER.error("AES decrypt error:",e);
        } catch (BadPaddingException e) {
            LOGGER.error("AES decrypt error:",e);
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            LOGGER.error("AES decrypt error:",e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error("AES decrypt error:",e);
        }
        return null;
    }

    /**
     * 微信小程序用户信息解密
     *
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] resultByte = decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                String info = new String(resultByte, "UTF-8");
                return info;
            }
        } catch (Exception e) {
            LOGGER.error("AES decrypt error:",e);
//            e.printStackTrace();
        }
        return null;
    }

    public static void initialize() {
        if (initialized) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

//    public static void main(String[] args) {
//        String encryptedData, sessionKey, iv, appId;
//        encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM" +
//                "QmRzooG2xrDcvSnxIMXFufNstNGTyaGS" +
//                "9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+" +
//                "3hVbJSRgv+4lGOETKUQz6OYStslQ142d" +
//                "NCuabNPGBzlooOmB231qMM85d2/fV6Ch" +
//                "evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6" +
//                "/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw" +
//                "u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn" +
//                "/Hz7saL8xz+W//FRAUid1OksQaQx4CMs" +
//                "8LOddcQhULW4ucetDf96JcR3g0gfRK4P" +
//                "C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB" +
//                "6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns" +
//                "/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd" +
//                "lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV" +
//                "oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG" +
//                "20f0a04COwfneQAGGwd5oa+T8yO5hzuy" +
//                "Db/XcxxmK01EpqOyuxINew==";
//        sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
//        iv = "r7BXXKkLb8qrSNn05n0qiA==";
//        appId = "wx4f4bc4dec97d474b";
//        String info = decrypt(encryptedData, sessionKey, iv);
//        System.out.println(info);
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("encryptedData", encryptedData);
//        map.put("sessionKey", sessionKey);
//        map.put("iv", iv);
//        map.put("appId", appId);
//        Map<String, Object> map1 = new HashMap<String, Object>();
//        map1.put("wxapplet", map);
//        String wxapplet = JSON.toJSON(map1).toString();
//        System.out.println(wxapplet);
//
//    }

    // 加密
    public static String Encrypt(String content, String key) throws Exception {
        if (key == null) {
            throw new BusinessException( "AES KEY 不能为空！");
        }
        // 判断Key是否为16位
        if (key.length() != 16 && key.length() != 32) {
            throw new BusinessException("AES KEY 长度错误！");
        }
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
        return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String Decrypt(String content, String key) throws Exception {
        try {
            // 判断Key是否正确
            if (key == null) {
                throw new BusinessException("AES KEY 不能为空！");
            }
            // 判断Key是否为16位
            if (key.length() != 16) {
                throw new BusinessException("AES KEY 长度错误！");
            }
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(content);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                throw new BusinessException("AES 解密失败！");
            }
        } catch (Exception ex) {
            throw new BusinessException("AES 解密失败");
        }
    }

}
